---
--类名: PhotoController.lua
--创建日期: 2018-7-30
--创建人: 宋建邦
--功能描述:拍照,分享逻辑
--修改内容:
--修改日期:
--修改人:
--修改备注:
local PhotoView = import(".PhotoView")
local PhotoViewShare = import(".PhotoViewShare")
local PhotoModel = import(".PhotoModel")
local PhotoModelShare = import(".PhotoModelShare")
local FatestoneShareView = import(".FatestoneShareView")

local fileName = string.getModeName(...)
local PhotoController = class(fileName, app.mvc.ControllerBase)

function PhotoController:ctor(params)
    self.super.ctor(self, params)
end

PhotoController.evtConfigChange = "photo.config.change"

function PhotoController:init()
    self.photoindex = 0
end

function PhotoController:showPhotoView(lastModel)
    -- cc.FileUtils:getInstance():removeFile(self:getSnapShotPath())
    NpcManager:hideAllNpcMark()
    NpcManager:allMapNpcsVisibility(false)
    FieldManager:updateAllCharactersUpHead(false)
    self.photoModel = lastModel
    if lastModel == nil then
    self.photoModel = PhotoModel.new()
    end

    self._isInPhoto = true
    self._enterMountTid = UD:getMountTID() or 0
    self._curMountTid = self._enterMountTid

    self.pv = PhotoView.new()
    self.pv:setLocalZOrder(1)
    self:addChild(self.pv)
    app:sendMsg("IMSimpleController", "showView", 
        Enums.IMSimpleShowType.btn, nil, nil, SceneZOrder.popupUIZOrder)

    self:set_filter(1)

    if lastModel then
        self:loadPhotoConfig(lastModel)
    end

    EM:notify("photo.openphotoview")
end

function PhotoController:loadPhotoConfig(cfg)
    if cfg then
        for k, v in pairs(cfg) do 
            self:photoModelChange(k, v)
        end
    end
end

function PhotoController:isInPhoto()
    return self._isInPhoto
end

function PhotoController:closePhotoView()
    NpcManager:showAllNpcMark()
    NpcManager:allMapNpcsVisibility(true)
    FieldManager:updateAllCharactersUpHead(true)

    self._isInPhoto = false
    if self._curMountTid ~= self._enterMountTid and self._enterMountTid ~= 0 then
        FieldManager:getMyCharacter():getOnRide(self._enterMountTid)
    end

    self:removeChild(self.pv)
    self.pv = nil
    self:set_filter(1)
    app:sendMsg("IMSimpleController", "showView")

    FieldManager:getWeatherSystem():setMap(MapManager:getMap())
    FieldManager:getWeatherSystem():initWeatherSystem()
    FieldManager:getWeatherSystem():playWeather()
    FieldManager:setHidingNotTeamCharacter(false)
    EM:notify("photo.closephotoview")
end

function PhotoController:showPhotoViewShare(fromePhotoView, photoCfg)
    if self.pvs then
        self:closePhotoViewShare()
    end

    local path = self:getSnapShotPath()
    if not cc.FileUtils:getInstance():isFileExist(path) then
        display.pushToast(L("PhotoShareSaveFail"))
        return 
    end

    self.pvs = PhotoViewShare.new()
    self.pvs:setLocalZOrder(1)
    self.pvs.fromePhotoView = fromePhotoView
    self.pvs.photoConfig = photoCfg
    self:addChild(self.pvs)
end

function PhotoController:closePhotoViewShare()
    self:removeChild(self.pvs)
    self.pvs = nil
    self:clearTmpNodes()
end

function PhotoController:showFatestoneShareView(chapterid)
    if self.fateShareView then
        self:closeFatestoneShareView()
    end
    self.fateShareView = FatestoneShareView.new(app.mvc.VIEWTYPE_BLUR, {cid=chapterid})
    self.fateShareView:setLocalZOrder(1)
    UIHandler:addSystemUi(self.fateShareView, self.fateShareView.__cname)
end

function PhotoController:closeFatestoneShareView()
    UIHandler:removeSystemUiByKey(self.fateShareView.__cname)
    self.fateShareView = nil
    self:clearTmpNodes()
end

function PhotoController:getPhotoModel()
    return self.photoModel
end

local function initFunc(itm, itmd, t)
    local pc = app:getInst("PhotoController")
    
    if pc:getPhotoModel()[t] == itmd.id then
        itm:findChild("Panel/selected"):show()
    else
        itm:findChild("Panel/selected"):hide()
    end
    
    itm:findChild("Panel/name"):setString(itmd.name)
    itm:findChild("Panel/Image"):loadTexture("art/photo/"..itmd.path)

    itm:findChild("Panel"):addTouchEventListener(
        function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                pc:getPhotoModel()[t] = itmd.id
                pc:notify(PhotoController.evtConfigChange)
                pc:photoModelChange(t, itmd.id)
            end
        end
    )
end

function PhotoController:disableButton()
    if self.pv then
        self.pv._root:findChild("Panel/selected_btn_2"):setTouchEnabled(false)
        self.pv._root:findChild("Panel/selected_btn_2"):setBright(false)
        display.setBtnGray(self.pv._root:findChild("Panel/selected_btn_2"), true)

        -- self.pv._root:findChild("Panel/selected_btn_4"):setTouchEnabled(false)
        -- self.pv._root:findChild("Panel/selected_btn_4"):setBright(false)
        -- display.setBtnGray(self.pv._root:findChild("Panel/selected_btn_4"), true)
    end
end

PhotoController.faceMenuData = {
    name=L("lua_code_text_15"),
    type="face",
    items={
        {id = 1, path="photo_img_emote_1.png", name=L("lua_code_text_303"), ani="mapidle"},
        {id = 2, path="photo_img_emote_2.png", name=L("lua_code_text_364"), ani="happy"},
        {id = 3, path="photo_img_emote_4.png", name=L("lua_code_text_25"), ani="celebrate"},
        {id = 4, path="photo_img_emote_3.png", name=L("lua_code_text_329"), ani="angry"},
        {id = 5, path="photo_img_emote_5.png", name=L("lua_code_text_350"), ani="surprised"},
        {id = 6, path="photo_img_emote_6.png", name=L("lua_code_text_91"), ani="confusion"},
        {id = 7, path="photo_img_emote_7.png", name=L("lua_code_text_339"), ani="seriously"},
        {id = 8, path="photo_img_emote_8.png", name=L("lua_code_text_192"), ani=nil},
    },
    itemInit = initFunc
}

PhotoController.envMenuData = {
    name=L("lua_code_text_133"),
    type="envirment",
    items={
        {id = 1, path="photo_img_huanj_1.png", name=L("lua_code_text_234")},
        {id = 2, path="photo_img_huanj_2.png", name=L("lua_code_text_316")},
        -- {id = 3, path="photo_img_huanj_2.png", name="大雨"},
        -- {id = 4, path="photo_img_huanj_1.png", name="小雪"},
        {id = 5, path="photo_img_huanj_3.png", name=L("lua_code_text_148")},
        -- {id = 6, path="photo_img_huanj_1.png", name="沙暴"},
        -- {id = 7, path="photo_img_huanj_1.png", name="雾气"},
        -- {id = 8, path="photo_img_huanj_1.png", name="闪电"},
    },
    itemInit = initFunc
}


PhotoController.frameMenuData = {
    name=L("lua_code_text_307"),
    type="frame",
    items={
        {id = 1, path="photo_img_logowz_0.png", name=L("lua_code_text_441")},
        {id = 2, path="photo_img_frame_2.png", name=L("lua_code_text_146")},
        {id = 3, path="photo_img_frame_1.png", name=L("lua_code_text_514")},
    },
    itemInit = initFunc
}


PhotoController.filterMenuData = {
    name=L("lua_code_text_282"),
    type="filter",
    items={
        {id = 1, path="photo_img_filter_1.png", name=L("lua_code_text_369")},
        {id = 2, path="photo_img_filter_2.png", name=L("lua_code_text_197")},
        -- {id = 3, path="photo_img_filter_3.png", name="黑白"},
        -- {id = 4, path="photo_img_filter_4.png", name="黑白"},
        -- {id = 5, path="photo_img_filter_5.png", name="黑白"},
        -- {id = 6, path="photo_img_filter_6.png", name="黑白"},
        -- {id = 7, path="photo_img_filter_7.png", name="黑白"},
        -- {id = 8, path="photo_img_filter_8.png", name="黑白"},
        -- {id = 9, path="photo_img_filter_3.png", name="黑白"},
    },
    itemInit = initFunc
}


PhotoController.logoMenuData = {
    name=L("lua_code_text_201"),
    type="logoPosition",
    items={
        {id = 1, path="photo_img_logowz_1.png", name=L("lua_code_text_187")},
        {id = 2, path="photo_img_logowz_3.png", name=L("lua_code_text_188")},
        {id = 3, path="photo_img_logowz_2.png", name=L("lua_code_text_454")},
        {id = 4, path="photo_img_logowz_4.png", name=L("lua_code_text_453")},
        {id = 5, path="photo_img_logowz_6.png", name=L("lua_code_text_199")},
        {id = 6, path="photo_img_logowz_7.png", name=L("lua_code_text_198")},
        {id = 7, path="photo_img_logowz_8.png", name=L("lua_code_text_365")},
        {id = 8, path="photo_img_logowz_9.png", name=L("lua_code_text_294")},
        {id = 9, path="photo_img_logowz_0.png", name=L("lua_code_text_28")},
    },
    itemInit = initFunc
}

function PhotoController:photoModelChange(t, id)
    local md = PhotoController[tostring(t).."MenuData"]
    local ret = {inter = false}
    if md and md.items[id] then
        EM:notify("photo.set.params", {type=t, id = id, data = md.items[id], ret = ret})
    end
    if self["set_"..tostring(t)] and ret.inter == false then
        self["set_"..tostring(t)](self, id)
    end
end

--表情
function PhotoController:set_face(id)
    local myCharacter = FieldManager:getMyCharacter()
    if not myCharacter then return end

    local aniConf = PhotoController.faceMenuData.items[id]
    if aniConf.ani then
        if self._curMountTid > 0 then
            myCharacter:setAction(aniConf.ani, false)
            myCharacter:getOffRide(true)
            self._curMountTid = 0
        else
            myCharacter:playAni(aniConf.ani, 0)
        end
    else
        if self._enterMountTid > 0 then
            myCharacter:setAction(aniConf.ani, false)
            myCharacter:getOnRide(self._enterMountTid)
            self._curMountTid = self._enterMountTid
        else
            display.pushToast(L("lua_code_text_18"))
        end
    end
end

--环境
function PhotoController:set_envirment(id)
    local wid = {111, --晴天
                2, --小雨
                2, --大雨
                13, --小雪
                13, --大雪
                141, --沙暴
                151, --雾气
                163, --闪电
                }

    if wid[id] then
        FieldManager:getWeatherSystem():playControl("play", wid[id])
    end
end

--外框
function PhotoController:set_frame(id)
    self.pv:setFrameType(id)
end

--滤镜
function PhotoController:set_filter(id)
    local Filters = {
        -- colors
        {},
        {"GRAY",{0.2, 0.3, 0.5, 0.1}},
        {"RGB",{1, 0.5, 0.3}},
        {"HUE", {90}},
        {"BRIGHTNESS", {0.3}},
        {"SATURATION", {0}},
        {"CONTRAST", {2}},
        {"EXPOSURE", {2}},
        {"GAMMA", {2}},
        {"HAZE", {0.1, 0.2}},
    }

    if id == 1 then
        MapManager:getMap():setFilter(nil)
    else
        local filters,params = unpack(Filters[id])
        MapManager:getMap():setFilter(filters,params)
    end
    
end

--logo位置
function PhotoController:set_logoPosition(id)
    self.pv:setLogoType(id)
end

--拍照
function PhotoController:snapshot()
    self.photoindex = self.photoindex + 1
    app:sendMsg("IMSimpleController", "hideView")
    display.captureScreen(function()
        app:sendMsg("IMSimpleController", "showView", 
            Enums.IMSimpleShowType.btn, nil, nil, SceneZOrder.popupUIZOrder)
    end, self:getSnapShotPath())
end

function PhotoController:snapshotNode(node, cb)
    local sz = node:getContentSize()

    local isQrVisible = false

    self:_snapshotNode({
        width = sz.width,
        height = sz.height,
        nodes = {node},
        clone = false,
        x = 0,
        y = 0,
        qr = isQrVisible,
        cb = cb,
    })
end

function PhotoController:snapshotNodes(nodes, w, h, x, y, cb)
    self:_snapshotNode({
        width = w or display.width,
        height = h or display.height,
        clone = true,
        x = x or 0,
        y = y or 0,
        nodes = nodes,
        cb = cb
    })
end

function PhotoController:_snapshotNode(pars)
    self.photoindex = self.photoindex + 1
    self:clearTmpNodes()

    local renderTexture = cc.RenderTexture:create(pars.width,pars.height)
    local qrpanel
    if pars.qr then
        qrpanel = self:getQRCodePanel()
        pars.nodes[1]:addChild(qrpanel)
    end

    renderTexture:begin()

    for _, v in ipairs(pars.nodes) do
        local tv = v
        if pars.clone then
            tv = v:clone()
            tv:retain()
            table.insert(self.tmpNodes, tv)
            tv:setPosition(tv:getPositionX() - pars.x, tv:getPositionY() - pars.y)
        end

        tv:visit()
    end

    renderTexture:endToLua()
    renderTexture:saveToFile(self:getSnapShotPath(), 1, true, function(texture, path)
        -- print("saveNodeShot.path", path)
        if pars.cb then
            executeFunc(pars.cb)
        end
    end)

    if pars.qr then
        qrpanel:removeFromParent()
    end
end

function PhotoController:clearTmpNodes()
    if self.tmpNodes and #self.tmpNodes > 0 then
        for i, v in ipairs(self.tmpNodes) do
            v:release()
        end
    end
    self.tmpNodes = {}
end

function PhotoController:getQRCodePanel()
    local panel = cc.CSLoader:createNode("ui2/main/photo_share_ewm.csb")
    local name = UD:getNickName()
    local lv = "LV "..tostring(UD.player.level)
    local serv = L(UD.zoneName)
    panel:findChild("Panel/text"):setString(name.." "..lv.." "..serv)
    panel:findChild("Panel"):setContentSize(display.size)

    if app:getPublisher() == Enums.Publisher.ema then
        panel:findChild("Panel/ewm"):hide()
    end
    ccui.Helper:doLayout(panel:findChild("Panel"))
    
    -- local panel = ccui.Layout:create()
    -- panel:setContentSize(cc.size(200, 400))

    -- local qrcode = ccui.ImageView:create("/art/photo/qrcode.png")
    -- panel:addChild(qrcode)
    -- qrcode:setPosition(cc.p(100, 100))

    -- local x = 180
    -- local y = -50
    -- local nameLbl = cc.Label:createWithTTF(UD:getNickName(), "ui2/fonts/LiheiPro.TTF", 20)
    -- nameLbl:setAnchorPoint(cc.p(0, 0))
    -- nameLbl:setTextColor(cc.c4b(255,225,132,255))
    -- nameLbl:setPosition(cc.p(x, y + 150))
    -- panel:addChild(nameLbl)

    -- local lvLbl = cc.Label:createWithTTF("lv "..tostring(UD.player.level), "ui2/fonts/LiheiPro.TTF", 20)
    -- lvLbl:setAnchorPoint(cc.p(0, 0))
    -- lvLbl:setTextColor(cc.c4b(255,225,132,255))
    -- lvLbl:setPosition(cc.p(x, y+125))
    -- panel:addChild(lvLbl)

    -- local zoneLbl = cc.Label:createWithTTF(L(UD.zoneName), "ui2/fonts/LiheiPro.TTF", 20)
    -- zoneLbl:setAnchorPoint(cc.p(0, 0))
    -- zoneLbl:setTextColor(cc.c4b(255,225,132,255))
    -- zoneLbl:setPosition(cc.p(x, y+100))
    -- panel:addChild(zoneLbl)

    panel:setPosition(cc.p(display.width*0.5, 0))
    return panel
end

function PhotoController:getSnapShotPath()
    local filePath = self:getStorePath().."/capture_screen"..tostring(self.photoindex)..".png"
    return filePath
end

function PhotoController:getStorePath()
    if device.platform=="android" then
		local args = {}
		local sigs = "()Ljava/lang/String;"
		local ok, ret = luaj.callStaticMethod("org/cocos2dx/lib/Cocos2dxHelper", "getPublicWritePath", args, sigs)
		if not ok then
			print("fail get sdcard path")
            return app:getStorePath()
        end
        print("sdcard path", ret)
        return ret
	else
		return app:getStorePath()
	end
end

function PhotoController:getPhotoModelShare()
end


function PhotoController:showAllCharacter()
    -- FieldManager:showAllCharacter()
    FieldManager:setHidingNotTeamCharacter(false)
end

function PhotoController:hideOtherCharacter()
    -- FieldManager:showTeamCharacterAndHideOther()
    FieldManager:setHidingNotTeamCharacter(true)
end

return PhotoController